/**
 * Created by IntelliJ IDEA.
 * User: hubiao
 * DateTime: 2018/8/2 8:48
 **/
package com.blogs.service.site.impl;

import com.blogs.common.constant.Types;
import com.blogs.domain.db.Comment;
import com.blogs.domain.db.Content;
import com.blogs.domain.dto.StatisticsDto;
import com.blogs.domain.dto.cond.CommentCond;
import com.blogs.domain.dto.cond.ContentCond;
import com.blogs.mapper.AttAchMapper;
import com.blogs.mapper.CommentMapper;
import com.blogs.mapper.ContentMapper;
import com.blogs.mapper.MetaMapper;
import com.blogs.service.site.SiteService;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SiteServiceImpl implements SiteService {

    private static final Logger LOGGER = LoggerFactory.getLogger( SiteServiceImpl.class );

    @Resource
    private CommentMapper commentDao;

    @Resource
    private ContentMapper contentDao;

    @Resource
    private MetaMapper metaDao;

    @Resource
    private AttAchMapper attAchDao;


    @Override
    @Cacheable(value = "siteCache", key = "'comments_' + #p0")
    public List<Comment> getComments(int limit) {
        LOGGER.debug( "Enter recentComments method: limit={}", limit );
        if (limit < 0 || limit > 10) {
            limit = 10;
        }
        PageHelper.startPage( 1, limit );
        List<Comment> rs = commentDao.getCommentsByCond( new CommentCond() );
        LOGGER.debug( "Exit recentComments method" );
        return rs;
    }

    @Override
    @Cacheable(value = "siteCache", key = "'newArticles_' + #p0")
    public List<Content> getNewArticles(int limit) {
        LOGGER.debug( "Enter recentArticles method:limit={}", limit );
        if (limit < 0 || limit > 10) {
            limit = 10;
        }
        PageHelper.startPage( 1, limit );
        List<Content> rs = contentDao.getArticleByCond( new ContentCond() );
        LOGGER.debug( "Exit recentArticles method" );
        return rs;
    }

    @Override
    @Cacheable(value = "siteCache", key = "'statistics_'")
    public StatisticsDto getStatistics() {
        LOGGER.debug( "Enter recentStatistics method" );

        // 文章总数
        Long articles = contentDao.getArticleCount();

        // 评论总数
        Long comments = commentDao.getCommentCount();

        // 链接数
        Long links = metaDao.getMetasCountByType( Types.LINK.getType() );

        // 获取附件数
        Long attAches = attAchDao.getAttAchCount();

        StatisticsDto rs = new StatisticsDto();
        rs.setArticles( articles );
        rs.setComments( comments );
        rs.setLinks( links );
        rs.setAttachs( attAches );
        LOGGER.debug( "Exit recentStatistics method" );
        return rs;
    }
}
